//
//  AddRecordVC.m
//  DoNotRemember
//
//  Created by Jinniu on 2019/1/30.
//  Copyright © 2019年 Jinniu. All rights reserved.
//

#import "AddRecordVC.h"
#import "AddRecordCell.h"
#import "CategoryModel.h"
#import "DLPickerView.h"
#import "TagModel.h"
@interface AddRecordVC ()<UITableViewDelegate,UITableViewDataSource>{
    NSArray * _titleArr,*_valueArr;
    UITextView * _tv;
    NSMutableDictionary * _paraDic;
}
@property(nonatomic,strong)UITableView * myTab;
@end

@implementation AddRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _paraDic = [NSMutableDictionary new];
    self.title = self.model==nil?@"新增":@"修改";
    _titleArr = @[@"标题：",@"分类：",@"标签：",@"账号：",@"密码：",@"确认密码："];
    if (self.model!=nil) {
        _valueArr = @[self.model.title,self.model.category,self.model.tagStr,self.model.account,self.model.password,self.model.password];
        NSArray * keyArr = @[@"title",@"category",@"tagStr",@"account",@"password",@"verifyPassword"];
        for (int i=0;i<keyArr.count;i++) {
            NSString * key = keyArr[i];
            [_paraDic setValue:_valueArr[i] forKey:key];
        }
        [_paraDic setValue:self.model.remark forKey:@"remark"];
    }
    [self.view addSubview:self.myTab];
    [self createBottomBtn];
}
-(void)createBottomBtn{
    NSArray * nameArr = @[@"生成密码",@"保存"];
    CGFloat btnWidth = (IPHONE_WIDTH-30)/2.f;
    for (int i =0; i<nameArr.count; i++) {
        UIButton * botBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [botBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        botBtn.backgroundColor = ThemeColor;
        botBtn.cornerRadius = 5;
        botBtn.tag = 10 + i;
        [botBtn addTarget:self action:@selector(botBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        botBtn.frame = Frame(10+(btnWidth+10)*i, IPHONE_HEIGHT-50, btnWidth, 40);
        [self.view addSubview:botBtn];
    }
}
-(void)botBtnClick:(UIButton*)sender{
    if (sender.tag==10) {
        NSString * str = [self return16LetterAndNumber];
        [_paraDic setObject:str forKey:@"password"];
        [_paraDic setObject:str forKey:@"verifyPassword"];
        NSIndexPath *idxPassword=[NSIndexPath indexPathForRow:4 inSection:0];
        AddRecordCell * cellPwd = [_myTab cellForRowAtIndexPath:idxPassword];
        cellPwd.inputTF.text = str;
        NSIndexPath *idxVPassword=[NSIndexPath indexPathForRow:5 inSection:0];
        AddRecordCell * cellVPwd = [_myTab cellForRowAtIndexPath:idxVPassword];
        cellVPwd.inputTF.text = str;
    }else{
        NSArray * keyArr = @[@"title",@"account",@"password",@"verifyPassword"];
        NSArray * alertArr = @[@"请输入标题",@"请输入账户",@"请输入密码",@"请再次输入密码"];
        __block BOOL isgoOn = YES;
        [keyArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString * value = self->_paraDic[obj];
            if (value.length==0) {
                [Mytools warnText:alertArr[idx] status:Error];
                isgoOn = NO;
                *stop = YES;
            }
        }];
        if (!isgoOn) {
            return;
        }
        NSString * pwd = _paraDic[@"password"];
        NSString * vPwd = _paraDic[@"verifyPassword"];
        if (![pwd isEqualToString:vPwd]) {
            [Mytools warnText:@"两次密码不一致" status:Error];
            return;
        }
        NSString* where;
        MainViewCtrModel * mo ;
        if (self.model) {
            where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(bg_primaryKey),self.model.bg_id];
            mo = self.model;
        }else{
            mo = [MainViewCtrModel new];
        }
        mo.bg_tableName = MainViewCtrTab;
        mo.title = _paraDic[@"title"];
        mo.category = _paraDic[@"category"]?_paraDic[@"category"]:@"";
        mo.tagStr = _paraDic[@"tagStr"]?_paraDic[@"tagStr"]:@"";
        mo.account = _paraDic[@"account"];
        mo.password = _paraDic[@"password"];
        mo.remark = _tv.text?_tv.text:@"";
        if (self.model) {
            [mo bg_updateWhere:where];
        }else{
            [mo bg_save];
        }
        
        [Mytools warnText:@"保存成功" status:Success];
        if (self.refreshBlock) {
            self.refreshBlock();
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}
#pragma mark tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _titleArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==1) {
        UITableViewCell * normalCell = [tableView dequeueReusableCellWithIdentifier:@"normalCell"];
        if(!normalCell){
            normalCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"normalCell"];
        }
        normalCell.selectionStyle = UITableViewCellSelectionStyleNone;
        normalCell.textLabel.text = _titleArr[indexPath.row];
        normalCell.textLabel.font = [UIFont fontWithDevice:14];
        normalCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (self.model!=nil) {
            normalCell.detailTextLabel.text = self.model.category;
            normalCell.detailTextLabel.font = [UIFont fontWithDevice:14];
        }
        return normalCell;
    }else{
        AddRecordCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if(!cell){
            cell = [[AddRecordCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.titleLab.text = _titleArr[indexPath.row];
            if (indexPath.row==4||indexPath.row==5) {
                cell.inputTF.secureTextEntry = YES;
            }
        }
        if (self.model!=nil) {
            cell.inputTF.text = _valueArr[indexPath.row];
        }
        cell.inputBlock = ^(NSString *str) {
            switch (indexPath.row) {
                case 0:[self->_paraDic setValue:str forKey:@"title"];break;
                case 2:[self->_paraDic setValue:str forKey:@"tagStr"];break;
                case 3:[self->_paraDic setValue:str forKey:@"account"];break;
                case 4:[self->_paraDic setValue:str forKey:@"password"];break;
                case 5:[self->_paraDic setValue:str forKey:@"verifyPassword"];break;
                default:
                    break;
            }
        };
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 100;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row==1) {
        NSArray* finfAlls = [CategoryModel bg_findAll:CategoryTab];
        NSMutableArray * arr = [NSMutableArray new];
        for (CategoryModel * mo in finfAlls) {
            [arr addObject:mo.category];
        }
        DLPickerView * picker = [[DLPickerView alloc]initWithDataSource:arr.copy withSelectedItem:nil withSelectedBlock:^(id  _Nonnull item) {
            UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.detailTextLabel.text = item;
            [self->_paraDic setObject:item forKey:@"category"];
        }];
        [picker show];
    }
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView * footer = [UIView new];
    footer.backgroundColor = [UIColor whiteColor];
    UILabel * titleLab = [UILabel labelWithTitle:@"备注：" color:[UIColor blackColor] font:[UIFont fontWithDevice:14]];
    [footer addSubview:titleLab];
    titleLab.sd_layout.leftSpaceToView(footer, 10).topSpaceToView(footer, 10).heightIs(16);
    [titleLab setSingleLineAutoResizeWithMaxWidth:300];
    _tv = [UITextView new];
    if (self.model) {
        _tv.text = self.model.remark;
    }
    _tv.font = [UIFont fontWithDevice:14];
    _tv.layer.borderColor = LineColor.CGColor;
    _tv.layer.borderWidth = 1;
    _tv.cornerRadius = 5;
    _tv.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5);
    [footer addSubview:_tv];
    _tv.sd_layout.leftSpaceToView(titleLab, 5).rightSpaceToView(footer, 10).topEqualToView(titleLab).bottomSpaceToView(footer, 10);
    return footer;
}

-(UITableView*)myTab{
    if (_myTab == nil) {
        _myTab = [[UITableView alloc]initWithFrame:CGRectMake(0, kTopHeight, IPHONE_WIDTH, IPHONE_HEIGHT-kTopHeight-60) style:UITableViewStyleGrouped];
        _myTab.delegate = self;
        _myTab.dataSource = self;
    }
    return _myTab;
}
//返回16位大小写字母和数字
-(NSString *)return16LetterAndNumber{
    //定义一个包含数字，大小写字母的字符串
    NSString * strAll = @"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    //定义一个结果
    NSString * result = [[NSMutableString alloc]initWithCapacity:16];
    for (int i = 0; i < 16; i++){
        //获取随机数
        NSInteger index = arc4random() % (strAll.length-1);
        char tempStr = [strAll characterAtIndex:index];
        result = (NSMutableString *)[result stringByAppendingString:[NSString stringWithFormat:@"%c",tempStr]];
    }
    return result;
}
@end
